"""Logging initializer for DYVA.

- Configures root logger based on config.
- Ensures log directory exists via path_utils.
- Avoids duplicate handlers across repeated calls.
"""
from __future__ import annotations

import logging
import os
from logging import Handler
from pathlib import Path
from typing import Dict, Any

from .config_loader import load_config
from .path_utils import ensure_directories_from_config

_INITIALIZED = False


def setup_logging(config_path: str = "config/config.yaml") -> None:
    """Initialize logging using configuration.

    - Reads level from `logging.level` with env override `DYVA_LOG_LEVEL`.
    - Writes to `paths.processing_log`.
    - Adds StreamHandler for console.
    - If called multiple times, updates root/handlers level but avoids duplicate handlers.
    """
    global _INITIALIZED

    cfg: Dict[str, Any] = load_config(config_path)
    ensure_directories_from_config(config_path)

    # Configured level name
    level_name = (cfg.get("logging", {}).get("level") or "INFO").upper()
    # Environment override takes precedence
    env_level = os.getenv("DYVA_LOG_LEVEL")
    if env_level:
        level_name = env_level.upper()
    level = getattr(logging, level_name, logging.INFO)

    log_file = Path(cfg.get("paths", {}).get("processing_log", "data/logs/processing.log"))

    root = logging.getLogger()
    root.setLevel(level)

    # Update existing handlers' levels to reflect override
    for h in list(root.handlers):
        try:
            h.setLevel(level)
        except Exception:
            pass

    # Prevent duplicate handlers
    def _has_handler(path: Path) -> bool:
        for h in root.handlers:
            if isinstance(h, logging.FileHandler):
                try:
                    if Path(getattr(h, "baseFilename", "")) == path:
                        return True
                except Exception:
                    pass
        return False

    # File handler
    if not _has_handler(log_file):
        fh = logging.FileHandler(log_file, encoding="utf-8")
        fh.setLevel(level)
        fh.setFormatter(logging.Formatter(
            fmt="%(asctime)s %(levelname)s [%(name)s] %(message)s",
            datefmt="%Y-%m-%d %H:%M:%S",
        ))
        root.addHandler(fh)

    # Stream handler
    has_stream = any(isinstance(h, logging.StreamHandler) for h in root.handlers)
    if not has_stream:
        sh = logging.StreamHandler()
        sh.setLevel(level)
        sh.setFormatter(logging.Formatter(
            fmt="%(asctime)s %(levelname)s [%(name)s] %(message)s",
            datefmt="%H:%M:%S",
        ))
        root.addHandler(sh)

    _INITIALIZED = True

